'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface Order {
  id: number;
  orderNumber: number;
  customerName: string;
  totalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';
  createdAt: string;
  itemsCount: number;
}

export default function OrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');
  const [processingOrder, setProcessingOrder] = useState<Order | null>(null);
  const [updating, setUpdating] = useState(false);

  useEffect(() => {
    fetchOrders();
  }, []);

  const fetchOrders = async () => {
    try {
      const response = await fetch('/api/orders');
      if (!response.ok) {
        throw new Error('获取订单列表失败');
      }
      const data = await response.json();
      setOrders(data);
    } catch (error) {
      console.error('获取订单数据失败:', error);
      setError('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const getStatusText = (status: string) => {
    const statusMap = {
      'pending': '待支付',
      'paid': '已支付',
      'shipped': '已发货',
      'delivered': '已交付',
      'cancelled': '已取消'
    };
    return statusMap[status as keyof typeof statusMap] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      'pending': 'bg-yellow-100 text-yellow-800',
      'paid': 'bg-blue-100 text-blue-800',
      'shipped': 'bg-indigo-100 text-indigo-800',
      'delivered': 'bg-green-100 text-green-800',
      'cancelled': 'bg-red-100 text-red-800'
    };
    return colorMap[status as keyof typeof colorMap] || 'bg-gray-100 text-gray-800';
  };

  const updateOrderStatus = async (orderId: number, newStatus: Order['status']) => {
    setUpdating(true);
    setError('');
    
    try {
      const response = await fetch(`/api/orders/${orderId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ status: newStatus }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新订单状态失败');
      }

      // 更新本地状态
      setOrders(orders.map(order => 
        order.id === orderId ? { ...order, status: newStatus } : order
      ));
      
      setProcessingOrder(null);
      
    } catch (error: any) {
      console.error('更新订单状态失败:', error);
      setError(error.message);
    } finally {
      setUpdating(false);
    }
  };

  const getNextStatusOptions = (currentStatus: Order['status']) => {
    const options = {
      pending: ['paid', 'cancelled'],
      paid: ['shipped', 'cancelled'],
      shipped: ['delivered'],
      delivered: [],
      cancelled: []
    };
    return options[currentStatus];
  };

  const filteredOrders = filterStatus === 'all' 
    ? orders 
    : orders.filter(order => order.status === filterStatus);

  if (loading) return <div className="p-8">加载中...</div>;

  return (
    <div className="p-8">
      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/" className="text-gray-600 hover:text-gray-900">
            ← 返回首页
          </Link>
          <h1 className="text-3xl font-bold">订单管理</h1>
        </div>
        <div className="flex space-x-3">
          <button className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
            导出订单报表
          </button>
          <Link href="/orders/add" className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
            新建订单
          </Link>
        </div>
      </div>

      <div className="mb-6 grid grid-cols-1 md:grid-cols-5 gap-4">
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-gray-800">{orders.length}</div>
          <div className="text-sm text-gray-600">总订单数</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-yellow-600">{orders.filter(o => o.status === 'pending').length}</div>
          <div className="text-sm text-gray-600">待支付</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-blue-600">{orders.filter(o => o.status === 'paid').length}</div>
          <div className="text-sm text-gray-600">已支付</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-indigo-600">{orders.filter(o => o.status === 'shipped').length}</div>
          <div className="text-sm text-gray-600">已发货</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-green-600">{orders.filter(o => o.status === 'delivered').length}</div>
          <div className="text-sm text-gray-600">已完成</div>
        </div>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="p-4 bg-gray-50 border-b">
          <div className="flex space-x-4">
            <input
              type="text"
              placeholder="搜索订单号或客户..."
              className="px-3 py-2 border border-gray-300 rounded-md w-64"
            />
            <select 
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md"
            >
              <option value="all">所有状态</option>
              <option value="pending">待支付</option>
              <option value="paid">已支付</option>
              <option value="shipped">已发货</option>
              <option value="delivered">已交付</option>
              <option value="cancelled">已取消</option>
            </select>
            <input
              type="date"
              className="px-3 py-2 border border-gray-300 rounded-md"
              placeholder="选择日期"
            />
          </div>
        </div>

        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                订单号
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                客户姓名
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                订单金额
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                商品数量
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                订单状态
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                下单时间
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {filteredOrders.map((order) => (
              <tr key={order.id}>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                  ORD-{order.orderNumber.toString().padStart(6, '0')}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {order.customerName}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  ¥{order.totalAmount}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {order.itemsCount} 件
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 text-xs font-medium rounded-full ${getStatusColor(order.status)}`}>
                    {getStatusText(order.status)}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {new Date(order.createdAt).toLocaleDateString('zh-CN')}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <Link href={`/orders/${order.id}`} className="text-blue-600 hover:text-blue-900 mr-3">
                    查看详情
                  </Link>
                  <button 
                    onClick={() => setProcessingOrder(order)}
                    className="text-green-600 hover:text-green-900"
                  >
                    处理订单
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="mt-6 flex justify-between items-center">
        <div className="text-sm text-gray-600">
          显示 {filteredOrders.length} 条订单中的 1-{filteredOrders.length} 条
        </div>
        <div className="flex space-x-2">
          <button className="px-3 py-1 border border-gray-300 rounded-md text-sm">
            上一页
          </button>
          <button className="px-3 py-1 border border-gray-300 rounded-md text-sm bg-blue-600 text-white">
            1
          </button>
          <button className="px-3 py-1 border border-gray-300 rounded-md text-sm">
            下一页
          </button>
        </div>
      </div>

      {/* 处理订单模态框 */}
      {processingOrder && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-lg w-full max-w-md">
            <div className="p-6">
              <h3 className="text-xl font-semibold mb-4">处理订单 #{processingOrder.orderNumber.toString().padStart(6, '0')}</h3>
              
              <div className="mb-4">
                <div className="text-sm text-gray-600">客户: {processingOrder.customerName}</div>
                <div className="text-sm text-gray-600">金额: ¥{processingOrder.totalAmount}</div>
                <div className="text-sm text-gray-600">
                  当前状态: 
                  <span className={`ml-2 px-2 py-1 text-xs font-medium rounded-full ${getStatusColor(processingOrder.status)}`}>
                    {getStatusText(processingOrder.status)}
                  </span>
                </div>
              </div>

              <div className="space-y-3">
                <h4 className="font-medium text-gray-700">更新订单状态:</h4>
                
                {getNextStatusOptions(processingOrder.status).length > 0 ? (
                  getNextStatusOptions(processingOrder.status).map((status) => (
                    <button
                      key={status}
                      onClick={() => updateOrderStatus(processingOrder.id, status as Order['status'])}
                      disabled={updating}
                      className="w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                    >
                      {updating ? '处理中...' : `标记为${getStatusText(status)}`}
                    </button>
                  ))
                ) : (
                  <div className="text-center text-gray-500 py-4">
                    此订单状态无法进行进一步操作
                  </div>
                )}
              </div>

              <div className="pt-4 mt-4 border-t">
                <button
                  onClick={() => setProcessingOrder(null)}
                  className="w-full px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}